package com.lmind.core.gps.terminal;

import java.nio.ByteBuffer;

import com.lmind.core.gps.terminal.message.AbstractMessage;
import com.lmind.core.gps.terminal.protocol.JsonMessageCodec;
import com.lmind.core.gps.terminal.protocol.PacketCodec;
import com.lmind.core.message.MessageCodec;
import com.lmind.core.message.MessageCodecException;

public class DefaultMessageCodec implements MessageCodec {
	
	private JsonMessageCodec objectCodec = new JsonMessageCodec();
	
	private PacketCodec packetCodec = new PacketCodec();
	
	@Override
	public ByteBuffer encode(Object message) {
		try {
			ByteBuffer data = objectCodec.encode((AbstractMessage)message);
			return packetCodec.encode(data);
		} catch (Exception e) {
			throw new MessageCodecException(e);
		}
	}

	@Override
	public Object decode(ByteBuffer buf) {
		try {
			ByteBuffer data = packetCodec.decode(buf);
			if (data == null)
				return null;
			return objectCodec.decode(data);
		} catch (Exception e) {
			throw new MessageCodecException(e);
		}
	}
}
